<template>
  <div style="display: flex; width: 100%">
    <div class="modal-url-config-item">
      <el-input
        v-model="url"
        placeholder="请输入路由地址，或者使用下拉框动态生成路由地址"
        clearable
        class="input-item"
      ></el-input>
    </div>
    <div class="modal-url-config-item">
      <el-input
        v-model="api"
        placeholder="API地址"
        clearable
        class="input-item"
      ></el-input>
    </div>
    <div class="modal-url-config-item">
      <el-select
        v-model="selectValue.id"
        placeholder="选择菜单"
        @change="handleMenuChange"
        clearable
        class="input-item"
      >
        <el-option
          v-for="item in menuList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </div>
    <div class="modal-url-config-item">
      <el-select
        v-model="labelField"
        placeholder="选择label字段"
        clearable
        class="input-item"
      >
        <el-option
          v-for="item in fieldList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </div>
    <div class="modal-url-config-item">
      <el-select
        v-model="valueField"
        placeholder="选择value字段"
        clearable
        class="input-item"
      >
        <el-option
          v-for="item in fieldList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </div>
  </div>
</template>
<script setup>
/**
 * ra-list-select-config
 * 表格选择器配置组件
 *
 * 选中菜单和字段，自动生成此菜单地址对应查询URL和API
 */
import { ref, watch, onMounted } from 'vue';
import ActionAPI from '@/api/admin/dev/action';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => ['', '', '', ''], // [url, api, label, value]
  },
});
const emit = defineEmits(['update:modelValue']);
const selectValue = ref({ id: null, route: '' });
const url = ref('');
const api = ref('');
const labelField = ref('');
const valueField = ref('');
const menuList = ref([]);
const fieldList = ref([]);

/**
 * 加载菜单选项
 */
async function fetchMenuOptions() {
  try {
    const { data } = await ActionAPI.getUserMenuOptions();
    menuList.value = data;
    // 菜单加载完成后，尝试初始化值
    initializeValues(props.modelValue);
  } catch (err) {
    console.error('Failed to load menu options:', err);
    // 可以在这里向用户显示错误消息
  }
}

// 菜单选中事件
async function handleMenuChange(id) {
  selectValue.value.id = id;
  if (!id) {
    selectValue.value.route = '';
    fieldList.value = [];
    labelField.value = '';
    valueField.value = '';
    updateValues();
    return;
  }
  try {
    const selectedMenu = menuList.value.find((item) => item.id === id);
    selectValue.value.route = selectedMenu ? selectedMenu.route : '';
    const { data: fieldsData } = await ActionAPI.getFields({ menu_id: id });
    fieldList.value = fieldsData.hasId;
    // 如果当前选中的字段不在新的字段列表中，则清空字段选择
    if (
      labelField.value &&
      !fieldList.value.some((f) => f.value === labelField.value)
    ) {
      labelField.value = '';
    }
    if (
      valueField.value &&
      !fieldList.value.some((f) => f.value === valueField.value)
    ) {
      valueField.value = '';
    }
  } catch (err) {
    console.error('Error fetching fields:', err);
    // 同样，这里可以展示错误信息给用户
  }
  updateValues();
}

// 更新所有值
function updateValues() {
  // 生成URL（不包含查询字符串）
  url.value = selectValue.value.route;

  // 生成API（将/admin/role转换为admin.role/index）
  if (selectValue.value.route) {
    // 移除开头的斜杠，将斜杠替换为点号，最后加上/index
    api.value =
      selectValue.value.route.replace(/^\//, '').replace(/\//g, '.') + '/index';
  } else {
    api.value = '';
  }

  emit('update:modelValue', [
    url.value,
    api.value,
    labelField.value,
    valueField.value,
  ]);
}

// // 初始化值
// async function initializeValues(initialValue) {
//   if (!Array.isArray(initialValue) || initialValue.length < 4) {
//     url.value = '';
//     api.value = '';
//     labelField.value = '';
//     valueField.value = '';
//     selectValue.value = { id: null, route: '' };
//     fieldList.value = [];
//     return;
//   }

//   const [initialUrl, initialApi, initialLabel, initialValue] = initialValue;
//   url.value = initialUrl;
//   api.value = initialApi;
//   labelField.value = initialLabel;
//   valueField.value = initialValue;

//   if (!initialUrl) {
//     selectValue.value = { id: null, route: '' };
//     fieldList.value = [];
//     return;
//   }

//   // 尝试根据URL找到对应的菜单
//   const foundMenu = menuList.value.find((menu) => menu.route === initialUrl);

//   if (foundMenu) {
//     selectValue.value.id = foundMenu.id;
//     selectValue.value.route = foundMenu.route;
//     // 加载字段列表
//     try {
//       const { data: fieldsData } = await ActionAPI.getFields({
//         menu_id: foundMenu.id,
//       });
//       fieldList.value = fieldsData;
//     } catch (err) {
//       console.error('Error fetching fields during initialization:', err);
//     }
//   } else {
//     // 如果没有找到匹配的菜单，则清空选择
//     selectValue.value = { id: null, route: '' };
//     fieldList.value = [];
//   }
// }

// 初始化值
async function initializeValues(initialValue) {
  if (!Array.isArray(initialValue) || initialValue.length < 4) {
    url.value = '';
    api.value = '';
    labelField.value = '';
    valueField.value = '';
    selectValue.value = { id: null, route: '' };
    fieldList.value = [];
    return;
  }

  // 使用不同的变量名来接收第四个元素
  const [initialUrl, initialApi, initialLabel, initialValueField] =
    initialValue;
  url.value = initialUrl;
  api.value = initialApi;
  labelField.value = initialLabel;
  valueField.value = initialValueField; // 使用新的变量名

  if (!initialUrl) {
    selectValue.value = { id: null, route: '' };
    fieldList.value = [];
    return;
  }

  // 尝试根据URL找到对应的菜单
  const foundMenu = menuList.value.find((menu) => menu.route === initialUrl);

  if (foundMenu) {
    selectValue.value.id = foundMenu.id;
    selectValue.value.route = foundMenu.route;
    // 加载字段列表
    try {
      const { data: fieldsData } = await ActionAPI.getFields({
        menu_id: foundMenu.id,
      });
      fieldList.value = fieldsData.hasId;
    } catch (err) {
      console.error('Error fetching fields during initialization:', err);
    }
  } else {
    // 如果没有找到匹配的菜单，则清空选择
    selectValue.value = { id: null, route: '' };
    fieldList.value = [];
  }
}

// 监听各个字段的变化
watch(url, () => {
  emit('update:modelValue', [
    url.value,
    api.value,
    labelField.value,
    valueField.value,
  ]);
});

watch(api, () => {
  emit('update:modelValue', [
    url.value,
    api.value,
    labelField.value,
    valueField.value,
  ]);
});

watch(labelField, () => {
  emit('update:modelValue', [
    url.value,
    api.value,
    labelField.value,
    valueField.value,
  ]);
});

watch(valueField, () => {
  emit('update:modelValue', [
    url.value,
    api.value,
    labelField.value,
    valueField.value,
  ]);
});

// 监听modelValue的变化来回显
watch(
  () => props.modelValue,
  (newVal) => {
    initializeValues(newVal);
  },
  { immediate: true },
); // immediate: true 确保在组件挂载时立即执行一次

onMounted(() => {
  fetchMenuOptions();
});
</script>
<style scoped>
.modal-url-config-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  width: 20%;
}
.input-item {
  width: 100%;
}
</style>
